# coding: utf-8

import os
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import datetime

from cardSimilar import kNN
from dao import DAO


app = Flask(__name__)

UPLOAD_FOLDER = 'static/images'
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__), UPLOAD_FOLDER)


@app.route('/')
def index():
    count = DAO.count()
    return render_template('index.html', count=count)


@app.route('/upload', methods=['POST'])
def upload():
    f = request.files['file']
    filename = secure_filename(f.filename)
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%s")
    filename = "%s_%s" % (timestamp, filename)
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    try:
        from PIL import Image
        Image.open(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file',
                            filename=filename))
    except:
        return render_template('index.html', info="Make Sure Uploading a Image File!")


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    fullname = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    t1 = datetime.datetime.now()
    results = kNN(fullname)
    t2 = datetime.datetime.now()
    cost = (t2 - t1).total_seconds()
    return render_template('results.html',
                           namecard=os.path.join("images", filename),
                           results=results,
                           cost=cost)


if __name__ == '__main__':
    app.run(
        host="0.0.0.0",
        port=int("5000")
    )

